import xlrd
import json
import sys
import getopt
import os.path


def get_col_names(sheet, key_line):
    """
    获取列名称
    :param sheet: 工作表
    :param key_line:
    :return: 返回指定工作表所有列的名称
    """
    row_size = sheet.row_len(key_line)
    col_values = sheet.row_values(key_line, 0, row_size)
    column_names = []
    for value in col_values:
        column_names.append(value)
    return column_names


def get_row_data(row, column_names, data_type):
    """
    获取带有列名称的行数据
    :param row: 工作表中的行数据
    :param column_names: 该工作表所有列的名称
    :param data_type:
    :return: 返回带有列名称的行数据
    """
    if data_type == 1:
        row_data = []
        for cell in row:
            row_data.append(cell.value)
    else:
        row_data = {}
        counter = 0
        for cell in row:
            row_data[column_names[counter]] = cell.value
            counter += 1

    return row_data


def get_sheet_data(sheet, column_names, data_type, key_line):
    """
    获取该工作表的数据
    :param sheet: 工作表
    :param column_names: 该工作表所有列的名称
    :param data_type:
    :param key_line:
    :return: 返回该工作表的数据
    """
    n_rows = sheet.nrows
    sheet_data = []

    if data_type == 1:
        sheet_data.append(column_names)

    for idx in range(key_line+1, n_rows):
            row = sheet.row(idx)
            row_data = get_row_data(row, column_names, data_type)
            sheet_data.append(row_data)

    return sheet_data


def get_work_book_data(workbook, data_type, key_line):
    """
    获取工作簿的数据
    :param workbook: 指定一个工作薄
    :param data_type: 指定输出的格式是不是 array 类型
    :param key_line:
    :return:返回工作簿的数据
    """
    n_sheets = workbook.nsheets
    work_book_data = {}
    for idx in range(0, n_sheets):
        worksheet = workbook.sheet_by_index(idx)
        column_names = get_col_names(worksheet, key_line)
        sheet_data = get_sheet_data(worksheet, column_names, data_type, key_line)
        work_book_data[worksheet.name] = sheet_data

    return work_book_data


def usage():
    """

    :return:
    """
    print('用法:')
    print('  ' + sys.argv[0] + ' -i <file1> [option]')
    print('常规选项:')
    print('  -h, --help\t\t显示帮助信息。')
    print('  -i, --input\t\t设置目标 Excel 文件路径。')
    print('  -o, --output\t\t设置转换后生产文件路径。')
    print('  --data-type\t\t设置转换 Json 的数据类型\n\t\t\t值为 0 时， 输出格式如：{"Example1":0,"Example2":1}；'
          '值为 1 时，输出格式如：[["Example1","Example2"],[0,1]]')
    print('  --key-line\t\t设置目标 Excel 文件第几行做为输出 Json 文件的 key 值。\n\t\t\t很多游戏配置文档都是第一行做为中文说明，第二行才是英文的属性key，所以设置参数如 -k 1。')


def main():
    """
    主函数
    :return:
    """
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hoi:v", ["help", "data-type=", "input=", "output=", "key-line="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output_path = None
    input_file = None
    data_type = 0
    key_line = 0
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-i", "--input"):
            input_file = a
        elif o in ("-o", "--output"):
            output_path = a
        elif o == "--data-type":
            data_type = int(a)
        elif o == "--key-line":
            key_line = int(a)
        else:
            usage()
            sys.exit()

    if input_file == None:
        print("您没有设置的目标文件。")
    elif os.path.isfile(input_file):
        work_book = xlrd.open_workbook(input_file)
        work_book_data = get_work_book_data(work_book, data_type, key_line)
        for name in work_book_data:
            if output_path == None:
                output_path = os.path.split(input_file)[0]
            output_file = open(output_path + "\\" + name + ".json", "wb")
            output_source = json.dumps(work_book_data[name], sort_keys=True, indent=4, separators=(',', ": "))
            output_data = bytes(output_source, 'UTF-8')
            output_file.write(output_data)
            output_file.close()
            print("%s 转换成功。" % output_file.name)
    else:
        print("您设置的目标文件不存在。")


if __name__ == "__main__":
    if len(sys.argv) > 1:
        main()
    else:
        usage()
        sys.exit()
